package com.css.fxfzfxqh.modules.buildingResetUnitPrice.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.dict.service.DictService;
import com.css.fxfzfxqh.modules.buildingResetUnitPrice.verify.BuildingVerifyHandler;
import com.css.fxfzfxqh.modules.buildingResetUnitPrice.entity.BuildingResetUnitPriceEntity;
import com.css.fxfzfxqh.modules.buildingResetUnitPrice.repository.BuildingResetUnitPriceRepository;
import com.css.fxfzfxqh.modules.buildingResetUnitPrice.service.BuildingResetUnitPriceService;
import com.css.fxfzfxqh.modules.buildingResetUnitPrice.vo.ParamsVo;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.economicLossDE.entity.VillageTownHosPeoEntity;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.economicLossDE.repository.VillageTownHostPeoRepository;
import com.css.fxfzfxqh.util.CreateGson;
import com.css.fxfzfxqh.util.PlatformDateUtils;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.util.UUIDGenerator;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.css.fxfzfxqh.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@Service
@Slf4j
public class BuildingResetUnitPriceServiceImpl implements BuildingResetUnitPriceService {

    @Autowired
    BuildingResetUnitPriceRepository buildingResetUnitPriceRepository;
    @Autowired
    SysAreaService sysAreaService;
    @Autowired
    DictService dictService;
    @Autowired
    BuildingVerifyHandler buildingVerifyHandler;
    @Autowired
    SUserService sUserService;
    @Autowired
    SysRoleService sysRoleService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> upload(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setHeadRows(3);
        params.setVerifyHandler(buildingVerifyHandler);
        params.setNeedVerify(true);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<BuildingResetUnitPriceEntity> result = ExcelImportUtil.importExcelMore(inputStream, BuildingResetUnitPriceEntity.class, params);
            List<BuildingResetUnitPriceEntity> failList =  result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='4px' color='red'>导入失败,请修改后重新导入</font><br>");
                errorMsg.append("<font size='4px' color='red'>导入失败原因:</font>");
                for(BuildingResetUnitPriceEntity buildingResetUnitPriceEntity: failList){
                    errorMsg.append("<font size='4px' ><br>").append("第").append(buildingResetUnitPriceEntity.getRowNum() + 1).append("行： ").append(buildingResetUnitPriceEntity.getErrorMsg()).append("</font><br>");
                }
                map.put("res",res);
                map.put("mess",errorMsg);
                return map;
            }
            String userId = PlatformSessionContext.getUserID();
            List<BuildingResetUnitPriceEntity> resultData = result.getList();//解析excel
            if (PlatformObjectUtils.isNotEmpty(resultData)) {
                List<BuildingResetUnitPriceEntity> list = new ArrayList<>();
                for (BuildingResetUnitPriceEntity buildingIndividualEntity : resultData) {
                    buildingIndividualEntity.setId(UUIDGenerator.getUUID());
                    String province = buildingIndividualEntity.getProvince();
                    String city = buildingIndividualEntity.getCity();
                    String county = buildingIndividualEntity.getCounty();
                    String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(province, "UTF-8"), URLEncoder.encode(city, "UTF-8"), URLEncoder.encode(county, "UTF-8"));
                    buildingIndividualEntity.setProvinceId(divisionIds.split("_")[0]);
                    buildingIndividualEntity.setCityId(divisionIds.split("_")[1]);
                    buildingIndividualEntity.setCountyId(divisionIds.split("_")[2]);

                    buildingIndividualEntity.setDelFlag("0");
                    String user = sUserService.getSUser(userId);
                    SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
                    buildingIndividualEntity.setCreateUser(userId);
                    buildingIndividualEntity.setCreateName(sUser.getUserName());
                    buildingIndividualEntity.setCreateTime(new Date());
                    list.add(buildingIndividualEntity);
                }
                for(BuildingResetUnitPriceEntity buildingResetUnitPriceEntity : list){
                    res = buildingResetUnitPriceRepository.save(buildingResetUnitPriceEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
            map.put("res",res);
            return map;
    }

    @Override
    public Map<String, Object> page(ParamsVo paramsVo, int curPage, int pageSize) {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        for(int i=0;i<maps.size();i++){
            Map map = maps.get(i);
            roles.append(map.get("roleCode")+",");
        }
        String allRole = roles.toString();
        String provinceId = sUser.getProvinceId();//省id
        Map<String, Object> map = buildingResetUnitPriceRepository.page(paramsVo, curPage, pageSize, allRole, provinceId);
        return map;
    }

    @Autowired
    private VillageTownHostPeoRepository villageTownHostPeoRepository;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(BuildingResetUnitPriceEntity buildingResetUnitPriceEntity) {
        /*String province = buildingResetUnitPriceEntity.getProvince();
        String city = buildingResetUnitPriceEntity.getCity();
        String county = buildingResetUnitPriceEntity.getCounty();
        String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(province, "UTF-8"), URLEncoder.encode(city, "UTF-8"), URLEncoder.encode(county, "UTF-8"));
        buildingResetUnitPriceEntity.setProvinceId(divisionIds.split("_")[0]);
        buildingResetUnitPriceEntity.setCityId(divisionIds.split("_")[1]);
        buildingResetUnitPriceEntity.setCountyId(divisionIds.split("_")[2]);
*/
        //TODO 临时代码  修改室内装修单价，暂时通过省市县来查找
        buildingResetUnitPriceEntity.getProvinceId();
        VillageTownHosPeoEntity villageTownHosPeoEntity = villageTownHostPeoRepository.findByProvinceIdAndCityIdAndPrefectureId(buildingResetUnitPriceEntity.getProvinceId(), buildingResetUnitPriceEntity.getCityId(), buildingResetUnitPriceEntity.getCountyId());
        if(PlatformObjectUtils.isNotEmpty(villageTownHosPeoEntity)){
            villageTownHosPeoEntity.setDhpTownIndoorProperty(BigDecimal.valueOf(Double.valueOf(buildingResetUnitPriceEntity.getDhpTownIndoorProperty())));
            villageTownHosPeoEntity.setDhpVillageIndoorProperty(BigDecimal.valueOf(Double.valueOf(buildingResetUnitPriceEntity.getDhpVillageIndoorProperty())));
        }else{
            VillageTownHosPeoEntity entity = new VillageTownHosPeoEntity();
            entity.setDhpTownIndoorProperty(BigDecimal.valueOf(Double.valueOf(buildingResetUnitPriceEntity.getDhpTownIndoorProperty())));
            entity.setDhpVillageIndoorProperty(BigDecimal.valueOf(Double.valueOf(buildingResetUnitPriceEntity.getDhpVillageIndoorProperty())));
            entity.setIsDelete("0");
            entity.setProvince(buildingResetUnitPriceEntity.getProvince());
            entity.setProvinceId(buildingResetUnitPriceEntity.getProvinceId());
            entity.setCity(buildingResetUnitPriceEntity.getCity());
            entity.setCityId(buildingResetUnitPriceEntity.getCityId());
            entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            entity.setCreateUser(PlatformSessionContext.getUserID());
            entity.setPrefecture(buildingResetUnitPriceEntity.getCounty());
            entity.setPrefectureId(buildingResetUnitPriceEntity.getCountyId());
            entity.setDhpId(UUIDGenerator.getUUID());
            villageTownHostPeoRepository.save(entity);
        }

        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        buildingResetUnitPriceEntity.setUpdateUser(userId);
        buildingResetUnitPriceEntity.setUpdateName(sUser.getUserName());
        buildingResetUnitPriceEntity.setUpdateTime(new Date());
        return buildingResetUnitPriceRepository.update(buildingResetUnitPriceEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(String ids) {
        boolean res= false;
        for(String id : ids.split(",")){
            res = buildingResetUnitPriceRepository.delete(id);
        }
        return res;
    }

    @Override
    public BuildingResetUnitPriceEntity findById(String id) {
        BuildingResetUnitPriceEntity  buildingResetUnitPriceEntity = buildingResetUnitPriceRepository.findById(id);
        if(PlatformObjectUtils.isNotEmpty(buildingResetUnitPriceEntity)){
            VillageTownHosPeoEntity villageTownHosPeoEntity = villageTownHostPeoRepository.findByProvinceIdAndCityIdAndPrefectureId(buildingResetUnitPriceEntity.getProvinceId(), buildingResetUnitPriceEntity.getCityId(), buildingResetUnitPriceEntity.getCountyId());
            if(PlatformObjectUtils.isNotEmpty(villageTownHosPeoEntity)){
                buildingResetUnitPriceEntity.setDhpVillageIndoorProperty(villageTownHosPeoEntity.getDhpVillageIndoorProperty().toString());
                buildingResetUnitPriceEntity.setDhpTownIndoorProperty(villageTownHosPeoEntity.getDhpTownIndoorProperty().toString());
            }
        }
        return buildingResetUnitPriceEntity;
    }
}
